#! /usr/bin/env python
# -*- coding: utf-8 -*-

# *************************************************************
#     Filename @  model.py
#       Author @  Huoty
#  Create date @  2015-12-18 10:54:37
#  Description @
# *************************************************************

from kwsite import app, db
from flask.ext.sqlalchemy import BaseQuery
from hashlib import sha1
from time import strftime, localtime
import json

# Script starts from here

class FavoritesQuery(BaseQuery):
    def getall(self):
        return self.all()

    def get_favorites_perpage(self, page, per_page):
        return self.order_by(Favorites.id.desc()).paginate(page, per_page, False)

class Favorites(db.Model):
    __tablename__ = 'favorites'
    query_class = FavoritesQuery

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), unique=True)
    url = db.Column(db.String(100))
    icon = db.Column(db.String(100))
    title = db.Column(db.Unicode(200))
    category = db.Column(db.String(80))

    def __init__(self, *args, **kwargs):
        super(Favorites, self).__init__(*args, **kwargs)

    def __repr__(self):
        return '<favorites name %r>' % self.name

class EssayQuery(BaseQuery):
    def getall(self):
        return self.all()

    def get_essays_perpage(self, page, per_page):
        return self.order_by(Essay.date.desc()).paginate(page, per_page, False)

class Essay(db.Model):
    __tablename__ = 'essay'
    query_class = EssayQuery

    id = db.Column(db.Integer, primary_key=True)
    date = db.Column(db.String(100), unique=True)
    content = db.Column(db.Text)

    def __init__(self, *args, **kwargs):
        super(Essay, self).__init__(*args, **kwargs)

    def __repr__(self):
        return '<essay date %r>' % self.date

class AlbumQuery(BaseQuery):
    def getall(self):
        return self.all()

class Album(db.Model):
    __tablename__ = 'album'
    query_class = EssayQuery

    id = db.Column(db.Integer, primary_key=True)
    url = db.Column(db.String(100))
    title = db.Column(db.String(200))

    def __init__(self, *args, **kwargs):
        super(Album, self).__init__(*args, **kwargs)

    def __repr__(self):
        return '<album url %r>' % self.url

class AdministratorQuery(BaseQuery):
    def getall(self):
        return self.all()

    def get_users_perpage(self, page, per_page):
        return self.order_by(Administrator.name.asc()).paginate(page, per_page, False)

    def get_users_perpage_by_purview(self, page, per_page, purview):
        return self.filter_by(purview = purview).order_by(Administrator.name.asc()).paginate(page, per_page, False)

class Administrator(db.Model):
    __tablename__ = 'administrator'
    query_class = AdministratorQuery

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), unique=True)
    passwd = db.Column(db.String(100))
    purview = db.Column(db.String(80))
    createdate = db.Column(db.String(80))

    def __init__(self, *args, **kwargs):
        super(Administrator, self).__init__(*args, **kwargs)

    def __repr__(self):
        return '<administrator name %r>' % self.name

class RecordQuery(BaseQuery):
    def get_last_record(self, username):
        return self.filter_by(username=username).order_by(Record.time.desc()).first()

class Record(db.Model):
    __tablename__ = 'record'
    query_class = RecordQuery
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80))
    time = db.Column(db.String(80), unique=True)
    ip = db.Column(db.String(60))

    def __init__(self, *args, **kwargs):
        super(Record, self).__init__(*args, **kwargs)

    def __repr__(self):
        return '<record ip %r>' % self.ip

def insert_record(username, time, ip):
    item = Record()
    item.username = username
    item.time = time
    item.ip = ip
    db.session.add(item)
    db.session.commit()



def import_urls(file_json):
    fd = open(file_json,'r')
    urls = json.load(fd)
    for category, entries in urls.iteritems():
        for entry in entries:
            item = Favorites()
            item.name = entry["name"]
            item.url = entry["url"]
            item.icon = entry["icon"]
            item.title = entry["title"]
            item.category = category
            db.session.add(item)
    db.session.commit()
    fd.close()

def import_essays(file_json):
    fd = open(file_json,'r')
    essays = json.load(fd)
    for date, essay in essays.iteritems():
        item = Essay()
        item.date = date
        item.content = essay
        db.session.add(item)
    db.session.commit()
    fd.close()

def initall():
    """
    Creates and init database tables
    """

    # create tables
    db.create_all()

    # initialize favorites
    item_fav = Favorites()
    item_fav.name = "百度"
    item_fav.url = "http://www.baidu.com"
    item_fav.icon = "http://www.baidu.com/favicon.ico"
    item_fav.title = "百度搜索引擎"
    item_fav.category = "se"
    db.session.add(item_fav)

    # initialize essay
    item_essay = Essay()
    item_essay.date = "2015-01-01"
    item_essay.content = "大道之行也，天下为公，选贤与能，讲信修睦。"
    db.session.add(item_essay)

    #initialize album
    item_album = Album()
    item_album.url = "http://7xixhp.com1.z0.glb.clouddn.com/al1_small.jpg"
    item_album.title = "哈哈哈哈"
    db.session.add(item_album)

    #initialize administrator
    item_admin = Administrator()
    item_admin.name = "guest"
    item_admin.passwd = sha1("123456").hexdigest()
    item_admin.purview = "general"
    item_admin.createdate = strftime("%Y-%m-%d %X", localtime())
    db.session.add(item_admin)

    #initialize record
    item_record = Record()
    item_record.username = "guest"
    item_record.time = "2015.01.01"
    item_record.ip = "0.0.0.0"
    db.session.add(item_record)

    # commit all
    db.session.commit()
